<!-- 显示摄像头、拍照示例 -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script type="text/javascript" src="js/jquery-1.11.0.min.js" ></script>
		<script type="text/javascript" src="js/echarts.min.js" ></script>
</head>
<body>
    <video id="video" width="640" height="480" autoplay></video>
    <button id="captureBtn">抓拍</button>

    <script>
        const video = document.getElementById('video')
        const captureBtn = document.getElementById('captureBtn')

        // 获取摄像头权限并启动摄像头
        navigator.mediaDevices.getUserMedia({ video: true })
            .then((stream) => {
                video.srcObject = stream
            })
            .catch((error) => {
                console.error('Error accessing the camera:', error)
            })
            function UrlToBlob(dataurl) {
              let arr = dataurl.split(','),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n);
              while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
              }
              return new Blob([u8arr], {
                type: mime
              })
            }
        // 捕获图像并保存到桌面
        captureBtn.addEventListener('click', () => {
            const canvas = document.createElement('canvas')
            canvas.width = video.videoWidth
            canvas.height = video.videoHeight
            const context = canvas.getContext('2d')
            context.drawImage(video, 0, 0, canvas.width, canvas.height)
            let fd = new FormData()
            fd.append('file', UrlToBlob(canvas.toDataURL('image/jpeg')), new Date().getTime() + '.jpeg')
            $.ajax({
              method: 'POST',
              url: 'http://localhost:8080/upload',
              data: fd,
              contentType: false,
              processData: false,
              success(res) {
                  console.log(res)
              }
          })
        });
    </script>
</body>
</html>